package ngvsa

import (
	"errors"
	"fmt"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"strings"
	"vrcm/src/vrcm/app/admin/models"
	"vrcm/src/vrcm/common/service"
	config "vrcm/src/vrcm/envconfig"
	ext "vrcm/src/vrcm/envconfig"
)

type NgvsaService struct {
	service.Service
}

var client = http.Client{}

func (e NgvsaService) GetResourceTarget(tenantId string, targetType string, resourceType string) (*gjson.Result, error) {
	if targetType == "node" {
		tenantId = strings.Split(tenantId, "vsnb")[0]
	}
	url := ""
	if resourceType == "station" {
		url = config.ExtConfig.ServiceConfig.NgvsaServiceUrl
	} else {
		url = fmt.Sprintf(`%s/v1/resource_relation/resource_authorization/%s?authorized_type=%s&resource_type=%s`, config.ExtConfig.ServiceConfig.NgvsaServiceUrl, tenantId, targetType, resourceType)
	}

	e.Log.Info("resource_target_url", url)
	request, err := http.NewRequest("GET", url, nil)
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		//e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil, err
	}

	res, err := client.Do(request)
	if err != nil {
		e.Log.Error(err)
		return nil, err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		//e.Log.Errorf("读取响应体失败 error:%s", err)
		return nil, err
	}
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return nil, errors.New(result.Get("message").String())
	}
	return &result, nil
}

// GetStreamHubInfo 获取StreamHub地址
func (e NgvsaService) GetStreamHubInfo(tenantId string, targetType string, resourceType string) (string, error) {

	if resourceType == "station" {
		return config.ExtConfig.ServiceConfig.NgvsaServiceUrl, nil
	}
	var streamHubUrl string
	data, err := e.GetResourceTarget(tenantId, targetType, resourceType)
	if err != nil {
		//e.Log.Error(err)
		return streamHubUrl, err
	}
	if data != nil {
		streamHubUrl = data.Get("data").Get("resource_target").Get("configuration").Get("api_gateway").String()
	}
	return streamHubUrl, nil
}
